/**
 * 
 */

package de.unihannover.se.restlab.microblog.resources;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import de.unihannover.se.restlab.microblog.data.AccountStorage;
import de.unihannover.se.restlab.microblog.data.UserStorage;
import de.unihannover.se.restlab.microblog.models.Account;
import de.unihannover.se.restlab.microblog.models.Link;
import de.unihannover.se.restlab.microblog.models.Role;
import de.unihannover.se.restlab.microblog.models.User;

@Path("users")
public class UserListResource {

	@Context
	UriInfo ui;

	@GET
	@Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public Response list () {
		List<User> users = UserStorage.getStorage().getUsers();

		for (User user : users) {
			Link self = new Link(ui.getAbsolutePathBuilder().path("{id}").build(user.getId()).toString(), "self");
			user.setSelf(self);
		}

// List<Message> messages = MessageStorage.getMessages();
//
// for (Message msg : messages) {
// Link self = new Link(ui.getAbsolutePathBuilder().path("{id}").build(msg.getId()).toString(), "self");
// msg.setSelf(self);
// }
		return Response.ok(users.toArray(new User[] {})).build();
	}

	@POST
	@Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Response create (@FormParam("name") String name, @FormParam("password") String password) {
		User user = UserStorage.getStorage().createUser(name);
		AccountStorage.getStorage().createAccount(user, Role.User, password);
		for (Account acc : AccountStorage.getStorage().getAccounts()) {
			System.out.println("AccID: " + acc.getAccountId() + ", Username: " + acc.getUser() + ", Passwort: " + acc.getPassword());
		}
		System.out.println(AccountStorage.getStorage().getAccounts());
		return Response.ok(user).build();
	}

	@Path("{id}")
	public UserResource getUserResource (@PathParam("id") Integer id) {
		return new UserResource(id);
	}

}
